package chapter06._01_ObjectClone;

import java.util.Date;

/*
 * @Description: 对象克隆 以及Cloneable接口的学习 不常用
 * @LastDate: 2020/9/27
 */
public class CloneTest {

    public static void main(String[] args) throws CloneNotSupportedException, InterruptedException {
        System.out.println("Not use clone");
        var init = new Test01(100);

        Test01 copy = init;// init和copy指向同一个对象 任何一个发生修改 对象就发生改变
        System.out.println("before: " + init.getId() + " " + init.getDate());
        Thread.sleep(1000);
        copy.change(50);
        System.out.println("after: " + init.getId() + " " + init.getDate());

        //如果要让copy指向新对象 且新旧对象的字段内容相同 此时就需要使用clone
        System.out.println("\nUse clone");
        Thread.sleep(1000);
        init = new Test01(100);
        Thread.sleep(500);
        /*before implements clone interface clone method cant work
        because of the clone method is protected*/
        copy = init.clone();
        System.out.println("before: " + init.getId() + " " + init.getDate());
        copy.change(50);
        System.out.println("after: " + init.getId() + " " + init.getDate());
    }
}

class Test01 implements Cloneable {
    private int id;
    private Date date;

    public Date getDate() {
        return date;
    }

    public Test01(int id) {
        this.id = id;
        this.date = new Date();
    }

    public int getId() {
        return id;
    }

    public void change(int id) {
        this.id += id;
        this.date = new Date();
    }

    /*
      复习protected
     */
    protected Test01 clone() throws CloneNotSupportedException {
        Test01 deepCopy = (Test01)super.clone();
        deepCopy.date = (Date)date.clone();

        return deepCopy;
    }
}
